using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.ServiceProcess;
using System.Threading;
using System.Runtime.InteropServices;
using Microsoft.Office.Project.EPMSync.Service.Monitor.Properties;
using System.Globalization;
using Microsoft.Office.Project.EPMSync.Config.Library;

namespace Microsoft.Office.Project.EPMSync.Service.Monitor
{
    public partial class FormMain : Form
    {

        [DllImport("user32.dll")]
        [return: MarshalAs(UnmanagedType.Bool)]
        static extern bool SetForegroundWindow(IntPtr hWnd);

        private ManualResetEvent _pause = new ManualResetEvent(false);
        private Thread _workerThread;
        private FormDisplay _fd;
        private FormTraceWindow _tw;
        private ServiceController _serviceController;

#if DEBUG
        private const string _epmSyncServiceName = "Spooler";
#else
        private const string _epmSyncServiceName = "EPMSyncService";
#endif
        public FormMain()
        {
            InitializeComponent();
            ConnectToEPMSync();
        }

        private void ConnectToEPMSync()
        {
            try
            {
                if (_serviceController == null)
                    _serviceController = new ServiceController(_epmSyncServiceName);

                toolStripMenuItemRunEPMSync.Enabled = true;
                _serviceController.Refresh();
                if (_serviceController.Status != ServiceControllerStatus.Running)
                    toolStripMenuItemRunEPMSync.Text = String.Format(CultureInfo.InvariantCulture, "{0} {1}", Resources.Start, _epmSyncServiceName);
                else
                    toolStripMenuItemRunEPMSync.Text = String.Format(CultureInfo.InvariantCulture, "{0} {1}", Resources.Stop, _epmSyncServiceName);
            }
            catch (ArgumentException)
            {
                _serviceController = null;
                toolStripMenuItemRunEPMSync.Enabled = false;
            }
        }

        private void frmMain_Load(object sender, EventArgs e)
        {
            // Spawn thread to get updates on the toolbar icon
            NotifyIconUpdate niu = new NotifyIconUpdate(this.notifyIcon1, _epmSyncServiceName, _pause);

            _workerThread = new Thread(new ThreadStart(niu.UpdateMethod));
            _workerThread.Start();
            _pause.Set();
        }

        private void frmMain_FormClosing(object sender, FormClosingEventArgs e)
        {
            _pause.Reset();
            _workerThread.Abort();
        }

        private void toolStripMenuItemExit_Click(object sender, EventArgs e)
        {
            if (_tw != null)
                _tw.Close();
            if (_fd != null)
                _fd.Close();

            this.Close();
        }

        private void toolStripMenuItemShow_Click(object sender, EventArgs e)
        {
            ShowDisplay();
        }

        private void notifyIcon1_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            ShowDisplay();
        }

        private void ShowDisplay()
        {
            if (_fd == null)
            {
                _fd = new FormDisplay();
                _fd.FormClosed += new System.Windows.Forms.FormClosedEventHandler(this.fd_FormClosed);
            }
            _fd.Show();
            SetForegroundWindow(_fd.Handle);
        }

        private void fd_FormClosed(Object sender, FormClosedEventArgs e)
        {
            _fd = null;
        }

        private void toolStripMenuItemShowTrace_Click(object sender, EventArgs e)
        {
            ShowTrace();
        }

        private void ShowTrace()
        {
            if (_tw == null)
            {
                _tw = new FormTraceWindow();
                _tw.FormClosed += new System.Windows.Forms.FormClosedEventHandler(this.tw_FormClosed);
                //_tw.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.tw_FormClosing);
            }
            _tw.Show();
            SetForegroundWindow(_tw.Handle);
        }

        private void tw_FormClosed(Object sender, FormClosedEventArgs e)
        {
            _tw = null;
        }

        //private void tw_FormClosing(Object sender, FormClosingEventArgs e)
        //{
        //    //_tw.Stop();
        //}

        private void toolStripMenuItemRunEPMSync_Click(object sender, EventArgs e)
        {
            try
            {
                if (_serviceController.Status != ServiceControllerStatus.Running)
                    _serviceController.Start();
                else
                    _serviceController.Stop();
            }
            catch (Win32Exception ex)
            {
                RightAwareMessageBox.Show(String.Format(CultureInfo.InvariantCulture, Resources.Win32Exception, ex.Message),
                    Resources.MonitorTitle, MessageBoxButtons.OK, MessageBoxIcon.Error);
                ConnectToEPMSync();
            }
            catch (InvalidOperationException ex)
            {
                RightAwareMessageBox.Show(String.Format(CultureInfo.InvariantCulture, Resources.ServiceException, ex.Message),
                    Resources.MonitorTitle, MessageBoxButtons.OK, MessageBoxIcon.Error);
                ConnectToEPMSync();
            }

        }

        private void contextMenuStrip1_Opening(object sender, CancelEventArgs e)
        {
            ConnectToEPMSync();
        }


    }
}